package com.minew.beaconset.permission;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

/**
 * 权限申请
 */
public class PermissionManager {
    public static PermissionManager get(Activity activity){
        return new PermissionManager(activity);
    }
    private Activity activity;
    private RxPermissions permissions ;
    public PermissionManager(Activity activity){
        this.activity = activity;
        this.permissions = new RxPermissions(activity);
    }
    public void check(String[] permission,AfterDo afterDo){
        permissions.request(
                permission)
                .subscribe(isOk -> {
                    if (isOk){
                        afterDo.onAfter();
                    }else{
                        showAlert(permission,afterDo);
                    }
                });
    }
    private void showAlert(String[] permission,AfterDo afterDo){
        String per = "";
        for(String p:permission){
            per+="\n"+p;
        }
        Dialog alertDialog = new AlertDialog.Builder(activity).
                setTitle("您需要授权以下权限给应用:").
                setMessage(per).
                setPositiveButton("确定", (dialog, which) -> {
                    check(permission,afterDo);
                }).
                setNegativeButton("取消", (dialog, which) -> {
                }).create();
        alertDialog.show();
    }
    public interface AfterDo{
        void onAfter();
    }
}
